package com.yanghui.agent.javassist;

import javassist.*;

import java.lang.reflect.Method;

public class TestJavassist {

    public static void main(String[] args) throws Exception {
        ClassPool pool = ClassPool.getDefault();
        /**
         * 创建class
         */
        CtClass ctClass = pool.makeClass("com.yanghui.agent.javassist.HelloWorld");
        /**
         * 创建方法
         */
        CtMethod mainMethod = new CtMethod(CtClass.voidType,"main",
                new CtClass[]{pool.get(String[].class.getName())},ctClass);
        mainMethod.setModifiers(Modifier.PUBLIC + Modifier.STATIC);
        mainMethod.setBody("{System.out.println(\"javassist hi helloworld by yanghui\");}");
        ctClass.addMethod(mainMethod);
        /**
         * 创建无参构造方法
         */
        CtConstructor ctConstructor = new CtConstructor(new CtClass[]{}, ctClass);
        ctConstructor.setBody("{}");
        ctClass.addConstructor(ctConstructor);
        /**
         * 输出类内容
         */
        ctClass.writeFile();
        /**
         * 测试调用
         */
        Class clazz = ctClass.toClass();
        Object obj = clazz.newInstance();
        Method main = clazz.getDeclaredMethod("main", String[].class);
        main.invoke(obj, (Object)new String[1]);
    }
}
